﻿using EmitMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zqdn.Services.Interfaces.ProvinceCity;
using zqdn.Web.Helpers;
using zqdn.Web.ViewModels;
using zqdn.Web.Extensions;
using zqdn.Web.App_Start;
using zqdn.Web.Filters;
using zqdn.Services.Auth;
using zqdn.Models.Auth;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data;

namespace zqdn.Web.Areas.Admin.Controllers
{

    public class UserController : Controller
    {
        private readonly IUserService _userService;
        private readonly ICityDetailsService _cityDetailservice;

        public UserController(ICityDetailsService cityDetailservice, IUserService userService)
        {
            this._cityDetailservice = cityDetailservice;
            this._userService = userService;
        }
        // GET: Admin/User
        [NormalAuthFilter(_role = (int)zqdn.Web.Helpers.Role.超级管理员)]
        public ActionResult Index(int? page = 1)
        {
            var users = _userService.GetUsers(page: (int)page, size: GlobalConfig.DefaultPageSize);
            var userViewModels = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<List<User>, List<ViewModels.UseriewModel>>().Map(users.ToList());
            var pagedList = new PagedList.StaticPagedList<ViewModels.UseriewModel>(userViewModels, users.GetMetaData());
            return View(pagedList);
        }

        #region 用户信息编辑
        [NormalAuthFilter(_role = (int)zqdn.Web.Helpers.Role.超级管理员)]
        public ActionResult Edit(int id)
        {
            return View();
        }

        [HttpPost]
        [NormalAuthFilter(_role = (int)zqdn.Web.Helpers.Role.超级管理员)]
        public ActionResult Edit(FormCollection collection)
        {
            return View();
        }
        #endregion

        #region 用户登录
        [AllowAnonymousAttribute]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection collection)
        {
            try
            {
                if (string.IsNullOrEmpty(collection["Username"]) || string.IsNullOrEmpty(collection["Password"]))
                {
                    return Json(new
                    {
                        statusCode = 200,
                        Msg = "请填写完整的登录信息！"
                    });
                }
                else
                {
                        var user = _userService.GetUserByMobile(collection["Username"]);
                        if (user == null)
                        {
                            return Json(new
                            {
                                Msg = "该用户不存在！"
                            });
                        }
                        else
                        {
                            if (user.RoleID != 0)
                            {
                                return Json(new
                                {
                                    Msg = "您还不是管理员，无权限操作！"
                                });
                            }
                            else
                            {
                                var re = _userService.UserLogin(collection["Username"], collection["Password"],"",1);
                                if (re == null)
                                    return Json(new { Msg = "登录失败,用户名或密码不正确，请稍后重试..." });

                                var userviewmodel = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<User, ViewModels.ApplicationUser>().Map(re);

                                SessionContext.SignIn(userviewmodel);
                                return Json(new { Msg = "登录成功,页面正在跳转...", Url = "/Admin/User/Index" });
                            }
                        }
                }
            }
            catch (Exception e)
            {
                return Json(new
                {
                    statusCode = 500,
                    Msg = e.Message
                });
            }

        }
        #endregion

        public ActionResult Logout()
        {
            SessionContext.SignOut();
            return RedirectToAction("Login", "User", new { area = "admin" });
        }


        public void ExportExcel()
        {
            String str = WebConfigurationManager.ConnectionStrings["DB_Zqdn"].ToString();
            SqlConnection conn = new SqlConnection();
            string sql = @"select a.ID 用户ID ,a.Mobile 用户手机号,a.Name 姓名,a.Province 省份,
                 a.City 城市,a.Area 区域,a.Hospital 医院,a.Deparment 科室,a.OpenID OpenID,a.CreatedTime 注册时间,
                a.ModifiedTime 最后更新时间,a.Integral 积分,a.NikeName 昵称,
                a.HeadImg 头像,b.SH 上传病例数,b.total 审核通过病例数
                 from users as a  
                 left join 
                (select b.CreateUserID,sum(case when status=1 then 1 else 0 end) SH ,COUNT(*) as total
                 from CaseTpls as b
                 group by CreateUserID) as b
                 on a.ID = b.CreateUserID";
            conn.ConnectionString = str;
            if (conn.State != System.Data.ConnectionState.Open)
            {
                conn.Open();
            }  
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            CreateExcel(table, "application/ms-excel","用户数据");
        }

        public void CreateExcel(DataTable dt, string FileType, string FileName)
        {
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.Buffer = true;
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
            Response.ContentType = FileType;
            string colHeaders = string.Empty;
            string ls_item = string.Empty;
            DataRow[] myRow = dt.Select();
            int i = 0;
            int cl = dt.Columns.Count;

            for (int key = 0; key < cl; key++)
            {
                Response.Output.Write(dt.Columns[key]+"\t");
            }
            Response.Output.Write("\n");

            foreach (DataRow row in myRow)
                {
                    for (i = 0; i < cl; i++)
                    {
                        if (i == (cl - 1))
                        {
                            ls_item += row[i].ToString().Replace("\r", "").Replace("\n", "") + "\n";
                        }
                        else
                        {
                            ls_item += row[i].ToString().Replace("\r", "").Replace("\n", "") + "\t";
                        }
                    }
                    Response.Output.Write(ls_item);
                    ls_item = string.Empty;
                }
            Response.Output.Flush();
            Response.End();
        }

    }
}